<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>排行榜 - 南宁二中2025级37班</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        :root {
            --primary: #1e88e5;
            --secondary: #64b5f6;
            --accent1: #e53935;
            --accent2: #43a047;
            --accent3: #fdd835;
            --accent4: #8e24aa;
            --dark: #2d3436;
            --light: #f5f6fa;
        }
        
        body {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            color: var(--dark);
            line-height: 1.6;
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        .container {
            width: 90%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 0;
        }
        
        /* 导航栏样式 */
        header {
            background: linear-gradient(90deg, var(--primary), var(--secondary), var(--accent1), var(--accent2));
            background-size: 400% 400%;
            animation: gradientShift 10s ease infinite;
            color: white;
            padding: 1rem 0;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        
        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 1.8rem;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .logo i {
            font-size: 2rem;
        }
        
        .nav-links {
            display: flex;
            list-style: none;
        }
        
        .nav-links li {
            margin-left: 1.5rem;
            position: relative;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
            padding: 0.5rem 1rem;
            border-radius: 30px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .nav-links a:hover {
            background-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }
        
        .nav-links a i {
            font-size: 1.1rem;
        }
        
        .user-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn-auth {
            padding: 0.6rem 1.2rem;
            border-radius: 30px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-login {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .btn-auth:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        /* 页面标题 */
        .page-header {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .page-header h1 {
            font-size: 2.5rem;
            color: var(--primary);
            margin-bottom: 0.5rem;
        }
        
        .page-header p {
            font-size: 1.2rem;
            color: #666;
            max-width: 600px;
            margin: 0 auto;
        }
        
        /* 排行榜切换选项卡 */
        .tabs {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
            background: white;
            border-radius: 15px;
            padding: 0.5rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .tab {
            padding: 1rem 2rem;
            cursor: pointer;
            font-weight: 500;
            border-radius: 10px;
            transition: all 0.3s;
            text-align: center;
            flex: 1;
            max-width: 200px;
        }
        
        .tab.active {
            background: var(--primary);
            color: white;
        }
        
        .tab:hover:not(.active) {
            background: rgba(30, 136, 229, 0.1);
        }
        
        /* 排行榜容器 */
        .leaderboard-container {
            display: none;
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            margin-bottom: 2rem;
        }
        
        .leaderboard-container.active {
            display: block;
            animation: fadeIn 0.5s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .leaderboard-header {
            padding: 1.5rem 2rem;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
        }
        
        .leaderboard-title {
            font-size: 1.5rem;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .leaderboard-body {
            padding: 0;
        }
        
        /* 排行榜表格样式 */
        .leaderboard-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .leaderboard-table th {
            background: #f8f9fa;
            padding: 1rem 1.5rem;
            text-align: left;
            font-weight: 600;
            color: #555;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .leaderboard-table th:hover {
            background: #e9ecef;
        }
        
        .leaderboard-table th i {
            margin-left: 0.5rem;
            opacity: 0.5;
        }
        
        .leaderboard-table td {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #eee;
        }
        
        .leaderboard-table tr:last-child td {
            border-bottom: none;
        }
        
        .leaderboard-table tr:hover {
            background: #f8f9fa;
        }
        
        /* 排名样式 */
        .rank {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
        }
        
        .rank-medal {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .rank-1 .rank-medal {
            background: #FFD700; /* 金牌 */
        }
        
        .rank-2 .rank-medal {
            background: #C0C0C0; /* 银牌 */
        }
        
        .rank-3 .rank-medal {
            background: #CD7F32; /* 铜牌 */
        }
        
        .rank-other .rank-medal {
            background: #6c757d;
        }
        
        /* 小组卡片样式 */
        .group-card-leaderboard {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .group-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .group-info {
            flex: 1;
        }
        
        .group-name {
            font-weight: 600;
            margin-bottom: 0.2rem;
        }
        
        .group-description {
            font-size: 0.9rem;
            color: #666;
        }
        
        /* 学生卡片样式 */
        .student-card-leaderboard {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .student-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .student-info {
            flex: 1;
        }
        
        .student-name {
            font-weight: 600;
            margin-bottom: 0.2rem;
        }
        
        .student-group {
            font-size: 0.9rem;
            color: #666;
        }
        
        /* 分数样式 */
        .score {
            font-weight: 600;
            font-size: 1.2rem;
            color: var(--primary);
        }
        
        /* 工具栏样式 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
            background: white;
            padding: 1.5rem;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .search-box {
            display: flex;
            align-items: center;
            background: var(--light);
            border-radius: 50px;
            padding: 0.5rem 1rem;
            width: 300px;
        }
        
        .search-box input {
            border: none;
            background: transparent;
            padding: 0.5rem;
            width: 100%;
            font-size: 1rem;
            outline: none;
        }
        
        .search-box i {
            color: #666;
        }
        
        .toolbar-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn {
            padding: 0.8rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* 页脚样式 */
        footer {
            background: linear-gradient(90deg, var(--dark), #3d3d3d);
            color: white;
            text-align: center;
            padding: 2.5rem 0;
            margin-top: 3rem;
            border-radius: 20px 20px 0 0;
        }
        
        .footer-content {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .footer-section {
            flex: 1;
            min-width: 200px;
        }
        
        .footer-section h3 {
            margin-bottom: 1.5rem;
            font-size: 1.3rem;
        }
        
        .footer-links {
            list-style: none;
        }
        
        .footer-links li {
            margin-bottom: 0.8rem;
        }
        
        .footer-links a {
            color: #ddd;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .footer-links a:hover {
            color: white;
        }
        
        .copyright {
            padding-top: 1.5rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            font-size: 0.9rem;
            color: #aaa;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .navbar {
                flex-direction: column;
                gap: 1rem;
            }
            
            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
            
            .nav-links li {
                margin: 0.5rem;
            }
            
            .user-actions {
                margin-top: 1rem;
            }
            
            .tabs {
                flex-direction: column;
                align-items: center;
            }
            
            .tab {
                width: 100%;
                max-width: none;
            }
            
            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }
            
            .search-box {
                width: 100%;
            }
            
            .toolbar-actions {
                width: 100%;
                justify-content: center;
            }
            
            .leaderboard-table {
                font-size: 0.9rem;
            }
            
            .leaderboard-table th,
            .leaderboard-table td {
                padding: 0.8rem 1rem;
            }
            
            .footer-content {
                flex-direction: column;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <header>
        <div class="container">
            <nav class="navbar">
                <div class="logo">
                    <i class="fas fa-school"></i>
                    <span>南宁二中2025级37班</span>
                </div>
                <ul class="nav-links">
                    <li><a href="index.html"><i class="fas fa-home"></i> 首页</a></li>
                    <li><a href="student_management.html"><i class="fas fa-user-graduate"></i> 学生管理</a></li>
                    <li><a href="group_management.html"><i class="fas fa-users"></i> 小组管理</a></li>
                    <li><a href="leaderboard.html" style="background-color: rgba(255, 255, 255, 0.3);"><i class="fas fa-trophy"></i> 排行榜</a></li>
                </ul>
                <div class="user-actions">
                    <button class="btn-auth btn-login" id="login-btn">
                        <i class="fas fa-sign-in-alt"></i> 教师登录
                    </button>
                </div>
            </nav>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1>排行榜</h1>
            <p>查看小组和学生的最新排名，追踪学习进步</p>
        </div>
        
        <!-- 工具栏 -->
        <div class="toolbar">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="search-input" placeholder="搜索小组或学生...">
            </div>
            <div class="toolbar-actions">
                <button class="btn btn-primary" id="refresh-btn">
                    <i class="fas fa-sync-alt"></i> 刷新数据
                </button>
            </div>
        </div>
        
        <!-- 排行榜切换选项卡 -->
        <div class="tabs">
            <div class="tab active" data-target="group-leaderboard">小组排行榜</div>
            <div class="tab" data-target="student-leaderboard">学生排行榜</div>
        </div>
        
        <!-- 小组排行榜 -->
        <div class="leaderboard-container active" id="group-leaderboard">
            <div class="leaderboard-header">
                <div class="leaderboard-title">
                    <i class="fas fa-users"></i> 小组排行榜
                </div>
            </div>
            <div class="leaderboard-body">
                <table class="leaderboard-table">
                    <thead>
                        <tr>
                            <th data-sort="rank">排名 <i class="fas fa-sort"></i></th>
                            <th data-sort="name">小组名称 <i class="fas fa-sort"></i></th>
                            <th data-sort="members">成员数量 <i class="fas fa-sort"></i></th>
                            <th data-sort="total">总分 <i class="fas fa-sort"></i></th>
                            <th data-sort="average">平均分 <i class="fas fa-sort"></i></th>
                        </tr>
                    </thead>
                    <tbody id="group-leaderboard-body">
                        <!-- 小组数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 学生排行榜 -->
        <div class="leaderboard-container" id="student-leaderboard">
            <div class="leaderboard-header">
                <div class="leaderboard-title">
                    <i class="fas fa-user-graduate"></i> 学生排行榜
                </div>
            </div>
            <div class="leaderboard-body">
                <table class="leaderboard-table">
                    <thead>
                        <tr>
                            <th data-sort="rank">排名 <i class="fas fa-sort"></i></th>
                            <th data-sort="name">学生姓名 <i class="fas fa-sort"></i></th>
                            <th data-sort="group">所在小组 <i class="fas fa-sort"></i></th>
                            <th data-sort="score">个人总分 <i class="fas fa-sort"></i></th>
                            <th data-sort="change">变化 <i class="fas fa-sort"></i></th>
                        </tr>
                    </thead>
                    <tbody id="student-leaderboard-body">
                        <!-- 学生数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer>
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h3>关于我们</h3>
                    <p>南宁二中2025级37班班级优化系统，致力于提升班级管理效率和学习积极性。</p>
                </div>
                <div class="footer-section">
                    <h3>快速链接</h3>
                    <ul class="footer-links">
                        <li><a href="index.html">首页</a></li>
                        <li><a href="student_management.html">学生管理</a></li>
                        <li><a href="group_management.html">小组管理</a></li>
                        <li><a href="leaderboard.html">排行榜</a></li>
                    </ul>
                </div>
                <div class="footer-section">
                    <h3>联系我们</h3>
                    <p>南宁市第二中学</p>
                    <p>2025级37班</p>
                </div>
            </div>
            <div class="copyright">
                <p>© 2023 南宁二中2025级37班 - 班级优化大师 | 所有权利保留</p>
            </div>
        </div>
    </footer>

    <script>
        // 修复URL解析问题 - 使用固定服务器地址
        const API_BASE_URL = 'http://localhost:5000';

        console.log('🌐 API基础URL:', API_BASE_URL);

        // 全局变量
        let groups = [];
        let students = [];
        let currentSort = {
            group: { field: 'total', direction: 'desc' },
            student: { field: 'score', direction: 'desc' }
        };
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', async function() {
            // 从后端加载数据
            await loadDataFromBackend();
            
            // 绑定事件
            bindEvents();
        });
        
        // 从后端加载数据
        async function loadDataFromBackend() {
            try {
                showLoadingState();
                
                console.log('正在从后端加载排行榜数据...');
                
                // 测试后端连接
                const testResponse = await fetch(API_BASE_URL + '/health');
                if (!testResponse.ok) {
                    throw new Error('后端服务器未响应');
                }
                
                // 并行加载所有数据
                const [groupsResponse, studentsResponse] = await Promise.all([
                    fetch(API_BASE_URL + '/api/groups').catch(e => { throw new Error('小组数据加载失败: ' + e.message) }),
                    fetch(API_BASE_URL + '/api/students').catch(e => { throw new Error('学生数据加载失败: ' + e.message) })
                ]);

                if (!groupsResponse.ok) throw new Error('小组数据响应错误: ' + groupsResponse.status);
                if (!studentsResponse.ok) throw new Error('学生数据响应错误: ' + studentsResponse.status);

                const groupsData = await groupsResponse.json();
                const studentsData = await studentsResponse.json();

                if (!groupsData.success) throw new Error('小组数据API错误: ' + groupsData.message);
                if (!studentsData.success) throw new Error('学生数据API错误: ' + studentsData.message);

                groups = groupsData.groups || [];
                students = studentsData.students || [];

                console.log('✅ 从后端加载排行榜数据成功:', {
                    groups: groups.length,
                    students: students.length
                });

                // 渲染排行榜
                renderGroupLeaderboard();
                renderStudentLeaderboard();
                
                showConnectionStatus('✅ 排行榜数据已更新', 'success');
                
            } catch (error) {
                console.error('❌ 从后端加载排行榜数据失败:', error);
                showConnectionStatus('❌ 排行榜数据更新失败: ' + error.message, 'error');
                
                // 使用模拟数据作为后备
                await loadMockData();
            }
        }
        
        // 加载模拟数据
        async function loadMockData() {
            console.log('使用模拟数据模式');
            
            students = [
                { id: 1, name: "李小明", total_score: 95, group_id: 1, student_id: "S001" },
                { id: 2, name: "张伟", total_score: 88, group_id: 2, student_id: "S002" },
                { id: 3, name: "王芳", total_score: 92, group_id: 1, student_id: "S003" },
                { id: 4, name: "刘洋", total_score: 78, group_id: 3, student_id: "S004" },
                { id: 5, name: "陈静", total_score: 85, group_id: 2, student_id: "S005" },
                { id: 6, name: "杨帆", total_score: 90, group_id: 4, student_id: "S006" },
                { id: 7, name: "黄磊", total_score: 82, group_id: 3, student_id: "S007" },
                { id: 8, name: "周涛", total_score: 96, group_id: 1, student_id: "S008" },
                { id: 9, name: "吴倩", total_score: 89, group_id: 5, student_id: "S009" },
                { id: 10, name: "郑华", total_score: 91, group_id: 4, student_id: "S010" }
            ];
            
            groups = [
                { 
                    id: 1, 
                    name: "第一组", 
                    description: "学习小组", 
                    total_score: 283,
                    students: students.filter(s => s.group_id === 1)
                },
                { 
                    id: 2, 
                    name: "第二组", 
                    description: "创新小组", 
                    total_score: 173,
                    students: students.filter(s => s.group_id === 2)
                },
                { 
                    id: 3, 
                    name: "第三组", 
                    description: "进步小组", 
                    total_score: 160,
                    students: students.filter(s => s.group_id === 3)
                },
                { 
                    id: 4, 
                    name: "第四组", 
                    description: "精英小组", 
                    total_score: 181,
                    students: students.filter(s => s.group_id === 4)
                },
                { 
                    id: 5, 
                    name: "第五组", 
                    description: "奋进小组", 
                    total_score: 89,
                    students: students.filter(s => s.group_id === 5)
                }
            ];
            
            renderGroupLeaderboard();
            renderStudentLeaderboard();
        }
        
        // 显示加载状态
        function showLoadingState() {
            const groupBody = document.getElementById('group-leaderboard-body');
            const studentBody = document.getElementById('student-leaderboard-body');
            
            groupBody.innerHTML = `
                <tr>
                    <td colspan="5" style="text-align: center; padding: 3rem;">
                        <i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: var(--primary); margin-bottom: 1rem;"></i>
                        <p>正在加载小组数据...</p>
                    </td>
                </tr>
            `;
            
            studentBody.innerHTML = `
                <tr>
                    <td colspan="5" style="text-align: center; padding: 3rem;">
                        <i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: var(--primary); margin-bottom: 1rem;"></i>
                        <p>正在加载学生数据...</p>
                    </td>
                </tr>
            `;
        }
        
        // 渲染小组排行榜
        function renderGroupLeaderboard() {
            const groupBody = document.getElementById('group-leaderboard-body');
            
            if (groups.length === 0) {
                groupBody.innerHTML = `
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 3rem;">
                            <i class="fas fa-users-slash" style="font-size: 2rem; color: #ccc; margin-bottom: 1rem;"></i>
                            <p>没有找到小组数据</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 按总分排序
            const sortedGroups = [...groups].sort((a, b) => {
                if (currentSort.group.field === 'total') {
                    return currentSort.group.direction === 'desc' ? 
                        b.total_score - a.total_score : a.total_score - b.total_score;
                } else if (currentSort.group.field === 'average') {
                    const avgA = a.students && a.students.length > 0 ? a.total_score / a.students.length : 0;
                    const avgB = b.students && b.students.length > 0 ? b.total_score / b.students.length : 0;
                    return currentSort.group.direction === 'desc' ? avgB - avgA : avgA - avgB;
                } else if (currentSort.group.field === 'members') {
                    const countA = a.students ? a.students.length : 0;
                    const countB = b.students ? b.students.length : 0;
                    return currentSort.group.direction === 'desc' ? countB - countA : countA - countB;
                } else if (currentSort.group.field === 'name') {
                    return currentSort.group.direction === 'desc' ? 
                        b.name.localeCompare(a.name) : a.name.localeCompare(b.name);
                }
                return 0;
            });
            
            groupBody.innerHTML = '';
            
            sortedGroups.forEach((group, index) => {
                const memberCount = group.students ? group.students.length : 0;
                const avgScore = memberCount > 0 ? Math.round(group.total_score / memberCount) : 0;
                const rankClass = index < 3 ? `rank-${index+1}` : 'rank-other';
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <div class="rank ${rankClass}">
                            <div class="rank-medal">${index + 1}</div>
                        </div>
                    </td>
                    <td>
                        <div class="group-card-leaderboard">
                            <div class="group-avatar">${group.name.charAt(0)}</div>
                            <div class="group-info">
                                <div class="group-name">${group.name}</div>
                                <div class="group-description">${group.description || '暂无描述'}</div>
                            </div>
                        </div>
                    </td>
                    <td>${memberCount}</td>
                    <td><span class="score">${group.total_score}</span></td>
                    <td><span class="score">${avgScore}</span></td>
                `;
                
                groupBody.appendChild(row);
            });
        }
        
        // 渲染学生排行榜
        function renderStudentLeaderboard() {
            const studentBody = document.getElementById('student-leaderboard-body');
            
            if (students.length === 0) {
                studentBody.innerHTML = `
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 3rem;">
                            <i class="fas fa-user-slash" style="font-size: 2rem; color: #ccc; margin-bottom: 1rem;"></i>
                            <p>没有找到学生数据</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 按分数排序
            const sortedStudents = [...students].sort((a, b) => {
                if (currentSort.student.field === 'score') {
                    return currentSort.student.direction === 'desc' ? 
                        b.total_score - a.total_score : a.total_score - b.total_score;
                } else if (currentSort.student.field === 'name') {
                    return currentSort.student.direction === 'desc' ? 
                        b.name.localeCompare(a.name) : a.name.localeCompare(b.name);
                } else if (currentSort.student.field === 'group') {
                    const groupA = groups.find(g => g.id === a.group_id) || { name: '未分组' };
                    const groupB = groups.find(g => g.id === b.group_id) || { name: '未分组' };
                    return currentSort.student.direction === 'desc' ? 
                        groupB.name.localeCompare(groupA.name) : groupA.name.localeCompare(groupB.name);
                }
                return 0;
            });
            
            studentBody.innerHTML = '';
            
            sortedStudents.forEach((student, index) => {
                const group = groups.find(g => g.id === student.group_id) || { name: '未分组' };
                const rankClass = index < 3 ? `rank-${index+1}` : 'rank-other';
                // 模拟排名变化
                const change = Math.floor(Math.random() * 5) - 2;
                const changeIcon = change > 0 ? 'fa-arrow-up' : change < 0 ? 'fa-arrow-down' : 'fa-minus';
                const changeColor = change > 0 ? 'var(--accent2)' : change < 0 ? 'var(--accent1)' : '#666';
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <div class="rank ${rankClass}">
                            <div class="rank-medal">${index + 1}</div>
                            ${change !== 0 ? `<span style="font-size: 0.8rem; color: ${changeColor};">${Math.abs(change)}</span>` : ''}
                        </div>
                    </td>
                    <td>
                        <div class="student-card-leaderboard">
                            <div class="student-avatar">${student.name.charAt(0)}</div>
                            <div class="student-info">
                                <div class="student-name">${student.name}</div>
                                <div class="student-group">学号: ${student.student_id || '未知'}</div>
                            </div>
                        </div>
                    </td>
                    <td>${group.name}</td>
                    <td><span class="score">${student.total_score}</span></td>
                    <td><i class="fas ${changeIcon}" style="color: ${changeColor};"></i></td>
                `;
                
                studentBody.appendChild(row);
            });
        }
        
        // 绑定事件
        function bindEvents() {
            // 选项卡切换
            document.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    const target = this.getAttribute('data-target');
                    
                    // 更新选项卡状态
                    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新排行榜显示
                    document.querySelectorAll('.leaderboard-container').forEach(container => {
                        container.classList.remove('active');
                    });
                    document.getElementById(target).classList.add('active');
                });
            });
            
            // 表格排序
            document.querySelectorAll('.leaderboard-table th').forEach(th => {
                th.addEventListener('click', function() {
                    const field = this.getAttribute('data-sort');
                    const leaderboardType = this.closest('.leaderboard-container').id;
                    
                    if (leaderboardType === 'group-leaderboard') {
                        if (currentSort.group.field === field) {
                            currentSort.group.direction = currentSort.group.direction === 'asc' ? 'desc' : 'asc';
                        } else {
                            currentSort.group.field = field;
                            currentSort.group.direction = 'desc';
                        }
                        renderGroupLeaderboard();
                    } else if (leaderboardType === 'student-leaderboard') {
                        if (currentSort.student.field === field) {
                            currentSort.student.direction = currentSort.student.direction === 'asc' ? 'desc' : 'asc';
                        } else {
                            currentSort.student.field = field;
                            currentSort.student.direction = 'desc';
                        }
                        renderStudentLeaderboard();
                    }
                    
                    // 更新排序图标
                    updateSortIcons();
                });
            });
            
            // 搜索功能
            document.getElementById('search-input').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                
                // 过滤小组排行榜
                const groupRows = document.querySelectorAll('#group-leaderboard-body tr');
                groupRows.forEach(row => {
                    const groupName = row.querySelector('.group-name').textContent.toLowerCase();
                    const groupDesc = row.querySelector('.group-description').textContent.toLowerCase();
                    const isVisible = groupName.includes(searchTerm) || groupDesc.includes(searchTerm);
                    row.style.display = isVisible ? '' : 'none';
                });
                
                // 过滤学生排行榜
                const studentRows = document.querySelectorAll('#student-leaderboard-body tr');
                studentRows.forEach(row => {
                    const studentName = row.querySelector('.student-name').textContent.toLowerCase();
                    const studentGroup = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
                    const isVisible = studentName.includes(searchTerm) || studentGroup.includes(searchTerm);
                    row.style.display = isVisible ? '' : 'none';
                });
            });
            
            // 刷新按钮
            document.getElementById('refresh-btn').addEventListener('click', async function() {
                const button = this;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
                button.disabled = true;
                
                await loadDataFromBackend();
                
                button.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新数据';
                button.disabled = false;
            });
        }
        
        // 更新排序图标
        function updateSortIcons() {
            // 重置所有图标
            document.querySelectorAll('.leaderboard-table th i').forEach(icon => {
                icon.className = 'fas fa-sort';
            });
            
            // 更新小组排行榜图标
            const groupHeader = document.querySelector('#group-leaderboard th[data-sort="' + currentSort.group.field + '"]');
            if (groupHeader) {
                const icon = groupHeader.querySelector('i');
                icon.className = currentSort.group.direction === 'asc' ? 
                    'fas fa-sort-up' : 'fas fa-sort-down';
            }
            
            // 更新学生排行榜图标
            const studentHeader = document.querySelector('#student-leaderboard th[data-sort="' + currentSort.student.field + '"]');
            if (studentHeader) {
                const icon = studentHeader.querySelector('i');
                icon.className = currentSort.student.direction === 'asc' ? 
                    'fas fa-sort-up' : 'fas fa-sort-down';
            }
        }
        
        // 显示连接状态
        function showConnectionStatus(message, type) {
            const existingStatus = document.getElementById('connection-status');
            if (existingStatus) {
                existingStatus.remove();
            }
            
            const statusEl = document.createElement('div');
            statusEl.id = 'connection-status';
            statusEl.innerHTML = `
                <div style="
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    padding: 10px 15px;
                    border-radius: 8px;
                    background: ${type === 'success' ? '#4CAF50' : type === 'warning' ? '#FF9800' : '#f44336'};
                    color: white;
                    font-size: 14px;
                    z-index: 1000;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
                ">
                    <i class="fas ${type === 'success' ? 'fa-check' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle'}"></i>
                    ${message}
                </div>
            `;
            
            document.body.appendChild(statusEl);
            
            setTimeout(() => {
                if (statusEl.parentNode) {
                    statusEl.remove();
                }
            }, 5000);
        }
    </script>
</body>
</html>